package com.asiainfo.complier.editor;

import com.asiainfo.complier.helper.StringHelper;

import javax.swing.text.BadLocationException;
import javax.swing.text.Highlighter;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.util.ArrayList;

public class WordHighter implements Highlighter.HighlightPainter {
	private ArrayList<Object> highterList;
	private LineEditor editor;

	public void removeAllHighter() {
		for (Object highterObject : highterList) {
			editor.getHighlighter().removeHighlight(highterObject);
		}
		highterList.clear();
	}

	public void addWordHighter() {
		String selectText = editor.getSelectedText();
		String allText = editor.getText();
		if (StringHelper.isNullOrEmpty(selectText)) {
			return;
		}
		int index = allText.indexOf(selectText);
		int strLen = selectText.trim().length();
		if (strLen < 2) {
			return;
		}
		while (true) {
			if (index == -1)
				break;
			else {
				int endIndex = allText.indexOf(selectText, index);
				if (endIndex == -1)
					break;
				else {
					try {
						Object highterObject = editor.getHighlighter()
								.addHighlight(index, index + strLen, this);
						highterList.add(highterObject);
					} catch (BadLocationException e) {
						e.printStackTrace();
					}
					index = endIndex + 1;
					if (index > allText.length())
						break;
					else {
						index = allText.indexOf(selectText, index);
					}
				}
			}
		}
	}

	public WordHighter(LineEditor editor) {
		highterList = new ArrayList<Object>();
		this.editor = editor;
	}

	public void paint(Graphics g, int p0, int p1, Shape bounds, JTextComponent c) {
		try {
			Rectangle rc = c.modelToView(p0);
			Rectangle endRc = c.modelToView(p1);
			g.setColor(Color.YELLOW);
			g.fill3DRect(rc.x, rc.y, endRc.x - rc.x, rc.height, true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
